<template>
  <el-main>
    <!--   搜索栏-->
    <el-form v-model="searchPram" label-width="80px" :inline="true" size="default">
      <el-form-item>
        <el-input placeholder="请输入关键字" v-model="searchPram.roleName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchBtn" icon="Search">搜索</el-button>
        <el-button @click="resetBtn" icon="Close" type="danger" plain>重置</el-button>
        <el-button type="primary" @click="addBtn" icon="Plus">新增</el-button>
      </el-form-item>
    </el-form>
    <!--    表格数据-->
    <el-table :data="tableList" border stripe :height="tableHeight">
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="remark" label="操作" width="auto" align="center">
        <template #default="scope">
          <el-button type="primary" @click="editBtn(scope.row)" icon="Edit">编辑</el-button>
          <el-button type="success" @click="assignBtn(scope.row)" icon="Edit">分配菜单</el-button>
          <el-button type="danger" @click="deleteBtn(scope.row.roleId)" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <el-pagination
        style="margin-top: 20px"
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="searchPram.currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="searchPram.pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="searchPram.total" background
    >
    </el-pagination>
    <!--    新增弹框-->
    <SysDialog
        :title="dialog.title"
        :width="dialog.width"
        :height="dialog.height"
        :visible="dialog.visible"
        @on-c-lose="onClose"
        @on-confirm="commit"
    >
      <template v-slot:content>
        <el-form :model="roleModel" ref="addRef" :rules="rules" label-width="80px" :inline="false" size="default">
          <el-form-item prop="roleName" label="角色名称">
            <!--input如果不绑定响应式数据会出现不能输入的现象-->
            <el-input v-model="roleModel.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input v-model="roleModel.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </SysDialog>
    <!--分配菜单-->
    <AssignTree ref="assingTree"></AssignTree>
  </el-main>
</template>

<script setup lang="ts">
import useDialog from '@/hocks/useDialog.ts'
//表单绑定对象
import {nextTick, onMounted, reactive, ref} from "vue";
import SysDialog from "@/components/SysDialog.vue";
import type {FormInstance} from 'element-plus'
import {ElMessage} from 'element-plus'
import {addApi, delApi, editApi, getListApi, isUsedApi} from "@/api/role";
import type {RolePram, SysRole} from "@/api/role/RoleModel.ts";
import useInstance from "@/hocks/useInstance.ts";
import type {Result} from "@/http";
import AssignTree from "@/views/system/role/AssignTree.vue";
import {useUserStore} from "@/store/user";

const userStore = useUserStore()
const {dialog, onShow, onClose} = useDialog()
const assingTree = ref()
//表单ref属性
const addRef = ref<FormInstance>()
//表单验证规则
const rules = reactive({
  roleName: {
    required: true,
    message: '角色名称不能为空',
    trigger: 'change'
  }
})
//表格高度
const tableHeight = ref(0)

//新增操作的表单数据
const roleModel: SysRole = reactive({
  roleId: '',
  roleName: '',
  remark: ''
})
//查询操作的表单数据
const searchPram: RolePram = reactive({
  currentPage: 1,
  pageSize: 10,
  roleName: '',
  total: 0
})
//表格数据
const tableList = ref([])
//查询
const getList = async () => {
  let res = await getListApi(searchPram)
  if (res && res.code == 200) {
    tableList.value = res.data.records
    //设置分页总条数
    searchPram.total = res.data.total
  }
}
onMounted(() => {
  dialog.height = 120
  //计算表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 310
  })
  getList()
})
//判断新增还是编辑,0:新增，1：编辑
const tags = ref('')
const addBtn = () => {
  tags.value = '0'
  dialog.title = '新增角色'
  onShow()
  //清空表单
  addRef.value?.resetFields()
}
const searchBtn = () => {
  getList()
}
const resetBtn = () => {
  searchPram.roleName = ''
  searchPram.currentPage = 1
  getList()
}
const editBtn = (row: SysRole) => {
  tags.value = '1'
  dialog.visible = true
  dialog.title = '编辑'
  //清空表单
  addRef.value?.resetFields()
  //回显数据,放在nextTick里 避免编辑之后关闭后再点新增时弹出无法清空数据的问题
  nextTick(() => {
    Object.assign(roleModel, row)
  })
}
const assignBtn = (row: SysRole) => {
  assingTree.value.show(userStore.getUserId, row.roleId, row.roleName)
}
//获取全局绑定的工具
const {global} = useInstance()
const deleteBtn = async (roleId: string) => {
  let res = await isUsedApi(roleId);
  if (res && res.code == 200) {
    if (!res.data) {
      const confirm = await global.$myConfirm('确定删除吗？')
      if (confirm) {
        let res = await delApi(roleId)
        if (res.code && res.code == 200) {
          ElMessage.success(res.msg)
          //刷新表格
          await getList()
        }
      }
    } else {
      ElMessage.error("角色被占用，不能删除！")
    }
  }
}
//页容量改变时触发
const sizeChange = (size: number) => {
  searchPram.pageSize = size
  getList()
}
//页数改变时触发
const currentChange = (page: number) => {
  searchPram.currentPage = page
  getList()
}
//表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {//验证通过
      //提交请求
      let res: Result<any>
      if (tags.value == '0') {
        res = await addApi(roleModel)  //新增
      } else {
        res = await editApi(roleModel) //编辑
      }
      if (res && res.code == 200) {
        ElMessage.success(res.msg)
        //刷新表格
        await getList()
        //关闭弹窗
        onClose()
      }
    }
  })
}
</script>

<style scoped>

</style>